#!/usr/bin/env python
sys.path.append("/work/opt/analytic/my_python/lib")
from lib.format_time import *
from lib.HandleMysql import *
from lib.switch_code import *
from jpype import *
import glob
import sys
import re
import os
sys.setdefaultencoding('utf-8')

class Service58(object):
    def __init__(self):
        self.jars = ':'.join(glob.glob('./java_lib/emc/*.jar'))
        startJVM(getDefaultJVMPath(),"-ea","-Djava.class.path=%s" % self.jars)
        self.SCFInit =JClass("com.bj58.spat.scf.client.SCFInit")
        self.SCFInit.init('./config/scf.config')
        
        URL= "tcp://emcproduct/ProductService" 
        self.ProxyFactory =JClass("com.bj58.spat.scf.client.proxy.builder.ProxyFactory")
        self.IProductService =JClass("com.bj58.ecat.emc.product.contract.IProductService")
        self.proxy = self.ProxyFactory.create(self.IProductService,URL)
        
        print "ok"
        
    def get_prod_count(self,shopId):
        self.shop_id = shopId
        self.query1 = "shopid=%s"%shopId
        self.prod_count = self.proxy.getCount(self.query1)
        
        self.query2 = "shopid=%s and state=1"%shopId
        self.prod_online_count = self.proxy.getCount(self.query2)
        
        return self.prod_count,self.prod_online_count
    
    def shut_down(self):
        shutdownJVM()
    
#mysql - stats
def set_stats_conn():    
    conn = HandleMysql('10.3.13.27','58885','ec_stat','L#c8UM5RGh5C','dbwww58com_58_stats')
    conn.connect()
    return conn

#mysql - shop
def set_shop_conn():    
    conn = HandleMysql('192.168.10.82','58885','shopuser_fenxi',"mYmq6U.^~V",'dbwww58com_shopemc')
    conn.connect()
    return conn

#mysql - product
def set_prod_conn():    
    conn = HandleMysql('192.168.12.28','58885','rdpln58read',"H5t8uV59niBZ5ABe5",'dbwww58com_plibrarynew')
    conn.connect()
    return conn


def get_newest_shop():
    conn = set_stats_conn()
    query = "select ifnull(max(shop_id),0) from shop_info"
    items = conn.get_results(query)
    maxid = items[0][0]
    
    return maxid
    
#logic
def execute( param ):
    
    query = ""
    #print param
    conn = set_shop_conn()
    s58=Service58()
    #
    if(param == "0"):
        maxid = get_newest_shop()
        query = "select id,userId,shopName,state,intro,banner,shoplogo from shop where id>%s"%maxid
    elif(param == "1"):
        maxid = 0
        query = "select id,userId,shopName,state,intro,banner,shoplogo from shop where id>%s"%maxid
    else:
        query = "select id,userId,shopName,state,intro,banner,shoplogo from shop where id=%s"%param
    
    #print query
    items = conn.get_results(query)
    for item in items:
        shopId = item[0]
        userId = item[1]
        shopName = item[2]
        state = item[3]
        intro = item[4]
        
        banner = item[5]
        
        if banner != None:
            banner = banner[2:34]
            
        logo = item[6]
        
        sql_album = "select count(1) from album where shopid=%s"%shopId;
        items_album = conn.get_results(sql_album)
        album_count = items_album[0][0]
        
        sql_pic = "select count(1) from pic where state=0 and  shopid=%s"%shopId;
        items_pic = conn.get_results(sql_pic)
        pic_count = items_pic[0][0]
       
        memo_count = 0
        sql_memo = "select entityText from memo where entityid=%s and entitytype=100001 limit 1"%shopId;
        items_memo = conn.get_results(sql_memo)
        try:
            if items_memo != None:
                txt = items_memo[0][0]     
                pattern =  re.compile(r'jpg')
                matchs = pattern.findall(txt)
                memo_count = len(matchs)
        except Exception,e:
                a=1
            #print memo_count
        #print "get prod count"
        prod_count,prod_online_count = s58.get_prod_count(shopId);
        #print prod_count,prod_online_count
        
        sh_cnt = get_shop_count(shopId)
        if sh_cnt == 0:        
            param = [shopId,userId,shopName,intro,logo,banner,state,prod_count,prod_online_count,album_count,pic_count,memo_count]
            insert_shop_info(param)
        else:
            param = {"user_id":userId,"shop_name":shopName,"intro":intro,"logo":logo,"banner":banner,"state":state,"prod_count":prod_count,"prod_online_count":prod_online_count,"album_count":album_count,"pic_count":pic_count,"memo_count":memo_count}
            cond = {"shop_id":shopId}
            update_shop_info(param,cond)
    #shut down jvm
    #s58.shut_down()
    
def get_shop_count(shop_id):
    conn = set_stats_conn()
    query = "select count(1) from shop_info where shop_id=%s"%shop_id
    items = conn.get_results(query)
    cnt = items[0][0]
    
    return cnt;
    
def insert_shop_info(param):
    conn = set_stats_conn()
    stat_table = "shop_info"
    try:
	conn.insert_record(stat_table,param)
    except Exception,e:
        print e
def update_shop_info(param,cond):
    conn = set_stats_conn()
    stat_table = "shop_info"
    try:
        conn.update_record(stat_table,param,cond)
    except Exception,e:
        print cond
def main():

   #date = '2012-05-28'
   #execute(date)
   param = 0;
   if len(sys.argv)==2:
        param=sys.argv[1]
        
   print "start"
   execute( param) 
   print "end"


if __name__=='__main__':
    #print os.getenv("PATH")
    #s58=Service58()
    #print s58.get_prod_count(5067738933761)
    main()
